package com.example.live.adapter

import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.live.R
import com.example.live.entity.LiveEntityItem


class LiveAdapter : BaseQuickAdapter<LiveEntityItem, BaseViewHolder>(R.layout.item_live) {
    private var isResume = false
   private var currentPlayer: ExoPlayer? = null
   private var currentPosition = -1
   private val players = mutableMapOf<Int, ExoPlayer>() // 存储每个位置的播放器

    // 预加载相关
    private val preloadHandler = Handler(Looper.getMainLooper())
    private var preloadRunnable: Runnable? = null
    private val preloadQueue = mutableListOf<Int>()
    private var isPreloading = false

    fun setResume(resume: Boolean) {
        isResume = resume
    }

    override fun convert(holder: BaseViewHolder, item: LiveEntityItem) {
        holder.setText(R.id.live_title, "@${item.title}")
        holder.setText(R.id.live_desc, item.description)
        val playerView = holder.getView<PlayerView>(R.id.playerView)

        // 重用或创建播放器
        val player = players[holder.bindingAdapterPosition] ?: run {
            ExoPlayer.Builder(context).build().apply {
                repeatMode = Player.REPEAT_MODE_ALL
                players[holder.bindingAdapterPosition] = this
            }
        }

        playerView.player = player
        val mediaItem = MediaItem.fromUri(item.videopath)

        // 确保在主线程设置媒体项
        if (Looper.myLooper() == Looper.getMainLooper()) {
            player.setMediaItem(mediaItem)
            player.prepare()
        } else {
            preloadHandler.post {
                player.setMediaItem(mediaItem)
                player.prepare()
            }
        }
        val signal = holder.getView<ImageView>(R.id.live_signal)
        val tv = holder.getView<TextView>(R.id.tv)
        val status = holder.getView<TextView>(R.id.live_status)
        player.addListener(object : Player.Listener{
            override fun onPlayerError(error: PlaybackException) {
                super.onPlayerError(error)
                playerView.visibility = View.GONE
                signal.visibility = View.GONE
                tv.text = "直播已结束"
                status.visibility = View.GONE
            }
        })

        player.playWhenReady = isResume && holder.bindingAdapterPosition == currentPosition

        holder.itemView.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View) {
                if (holder.bindingAdapterPosition == currentPosition) {
                    player.playWhenReady = true
                }
            }
            override fun onViewDetachedFromWindow(v: View) {
                player.playWhenReady = false
            }
        })
    }

     //提供给外部的方法，预加载指定位置的视频
    fun preloadNext(position: Int) {
        if (position < 0 || position >= data.size || isPreloading) return
        preloadQueue.add(position)
        if (preloadQueue.size == 1) {
            startPreloading()
        }
    }

    private fun startPreloading() {
        if (preloadQueue.isEmpty()) {
            isPreloading = false
            return
        }

        isPreloading = true
        val position = preloadQueue.removeAt(0)

        // 确保位置有效
        if (position < 0 || position >= data.size) {
            startPreloading()
            return
        }

        // 如果已经创建了播放器，跳过
        if (players.containsKey(position)) {
            startPreloading()
            return
        }

        // 在主线程创建播放器
        preloadHandler.post {
            val player = ExoPlayer.Builder(context).build().apply {
                repeatMode = Player.REPEAT_MODE_ALL
            }

            players[position] = player

            // 设置媒体项也在主线程
            val mediaItem = MediaItem.fromUri(data[position].videopath)
            player.setMediaItem(mediaItem)
            player.prepare()

            // 继续预加载队列中的下一个
            startPreloading()
        }
    }

    // 设置当前播放位置
    fun setCurrentPosition(position: Int) {
        if (position == currentPosition) return

        // 停止当前播放
        players[currentPosition]?.playWhenReady = false

        // 开始新的播放
        currentPosition = position
        if(isResume){
            players[position]?.playWhenReady = true
        }


        // 预加载相邻的视频
        preloadNext(position + 1) // 预加载下一个
        preloadNext(position - 1) // 预加载上一个
    }

    fun shop() {
        players[currentPosition]?.playWhenReady = false
    }

    fun start() {
        players[currentPosition]?.playWhenReady = true
    }

    fun release() {
        preloadRunnable?.let { preloadHandler.removeCallbacks(it) }
        players.values.forEach { it.release() }
        players.clear()
    }
}